<template>
    <div>
        <div ref="Pie" id="pie" class="pie" element-loading-text="获取数据中" element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"></div>
    </div>
</template>
<script setup lang='ts'>
import { onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';

//***引入
import * as echarts from 'echarts';

const props = defineProps({
    chartData: {
        type: Object,
        default: false
    },
});


watch(() => props.chartData, async val => {
    if (val) {
        initChart()
    }
}, { deep: true })

const colorList = [
    '#249EFF',
    '#846BCE',
    '#21CCFF',
    '#0E42D2',
    '#86DF6C',
    '#D95040'
]

let myChart: any = null
const resizeDom = ref()
const resizeEle = ref()

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const initChart = () => {
    // 招商
    const investmentdata = props.chartData.investment.map((item: any, index: number) => {
        return {
            ...item,
            itemStyle: {
                color: colorList[index],
            }
        }
    })
    // 产品
    const iproductdata = props.chartData.product.map((item: any, index: number) => {
        return {
            ...item,
            itemStyle: {
                color: colorList[index],
            }
        }
    })
    // 运营
    const operatedata = props.chartData.operate.map((item: any, index: number) => {
        return {
            ...item,
            itemStyle: {
                color: colorList[index],
            }
        }
    })
    let Pie: any = proxy?.$refs.Pie
    // @ts-ignore
    //  基于准备好的dom，初始化echarts实例
    myChart = echarts.init(Pie);
    // 指定图表的配置项和数据
    let option = {
        tooltip: {
            trigger: "item",
            formatter: "{b} :  {d}%",
        },
        toolbox: {
            show: false,
        },
        legend: {
            show: true,
            orient: 'horizontal',
            align: 'auto',
            icon: 'circle',
            bottom: '1%',
            itemGap: 10,
            textStyle: {
                color: '#000',
                fontSize: 10,
                rich: {
                    a: {
                        width: 20,
                        align: "left",
                    },
                }
            },
            data: investmentdata.map((v: any) => v.name),
            formatter: function (name: string) {
                let arr = [
                    "{a|" + name + "}"
                ];
                return arr.join("");
            },
        },
        series: [
            {
                name: '',
                type: 'pie',
                radius: ['40%', '55%'],
                center: ['18%', '50%'],
                avoidLabelOverlap: true,
                label: {
                    normal: {
                        show: true,
                        formatter: (params: any) => {
                            return params.percent + '%'
                        },
                    }
                },
                itemStyle: {
                    borderRadius: 2,
                    borderWidth: 2,
                },
                labelLine: {
                    show: true, //显示引导线
                    length: 10, //连接饼图第1段线条的长度 length length2 不写自适应
                    length2: 10, //链接饼图第2段线条长度
                    smooth: true, //是否光滑连接线
                },
                data: investmentdata
            },
            {
                name: '',
                type: 'pie',
                radius: ['40%', '55%'],
                center: ['50%', '50%'],
                avoidLabelOverlap: true,
                label: {
                    normal: {
                        show: true,
                        formatter: (params: any) => {
                            return params.percent + '%'
                        },
                    }
                },
                itemStyle: {
                    borderRadius: 2,
                    borderWidth: 2,
                },
                labelLine: {
                    show: true, //显示引导线
                    length: 10, //连接饼图第1段线条的长度 length length2 不写自适应
                    length2: 10, //链接饼图第2段线条长度
                    smooth: true, //是否光滑连接线
                },
                data: iproductdata
            },
            {
                name: '',
                type: 'pie',
                radius: ['40%', '55%'],
                center: ['82%', '50%'],
                avoidLabelOverlap: true,
                label: {
                    normal: {
                        show: true,
                        formatter: (params: any) => {
                            return params.percent + '%'
                        },
                    }
                },
                itemStyle: {
                    borderRadius: 2,
                    borderWidth: 2,
                },
                labelLine: {
                    show: true, //显示引导线
                    length: 10, //连接饼图第1段线条的长度 length length2 不写自适应
                    length2: 10, //链接饼图第2段线条长度
                    smooth: true, //是否光滑连接线
                },
                data: operatedata
            },
        ],
        graphic: <any>[] // 稍后添加文本标签  
    };

    addLabelsToGraphic(myChart, Pie, option);
    option && myChart.setOption(option);
    // 等待图表渲染完成后添加文本标签  
    nextTick().then(() => {
        addLabelsToGraphic(myChart, Pie, option);
    });
    // 监听窗口大小变化以重新计算文本标签位置（可选）  
    window.addEventListener('resize', () => {
        if (myChart) {
            nextTick().then(() => {
                addLabelsToGraphic(myChart, Pie, option);
            });
        }
    });
}

// 添加文本标签到 graphic 配置中  
const addLabelsToGraphic = (myChart: any, Pie: any, option: any) => {
    if (!myChart || !Pie) return;

    const containerWidth = Pie.offsetWidth;

    const labels = [
        { text: '招商部', centerX: '18%', centerY: '50%', left: 33 },
        { text: '产品部', centerX: '50%', centerY: '50%', left: 37 },
        { text: '运营部', centerX: '82%', centerY: '50%', left: 41 },
    ];
    option.graphic = labels.map(label => {
        const x = containerWidth * parseFloat(label.centerX) / 100 - label.left;
        return {
            type: 'text',
            left: x,
            top: '47%', // 向上偏移以适应饼图中心  
            style: {
                text: label.text,
                fill: '#000',
                fontSize: 20,
                textAlign: 'center',
            },
        };
    });

    myChart.setOption(option);
};

window.addEventListener("resize", () => {
    myChart.resize()
});

//*** 挂载Echarts
onMounted(() => {
    initChart()
    resizeDom.value = document.getElementById('pie')
    resizeEle.value = new ResizeObserver((entries) => {
        myChart.resize()
        addLabelsToGraphic(myChart, proxy?.$refs.Pie, myChart.getOption());
    })
    resizeEle.value.observe(resizeDom.value as HTMLElement)
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', () => {
        myChart.resize()
    });
    resizeEle.value.disconnect(resizeDom.value)
})



</script>
<style scoped lang="scss">
.pie {
    width: 100%;
    height: 100%;
}
</style>